package club.ruanx.spider.async;

import club.ruanx.mq.common.entity.MessageData;
import club.ruanx.spider.DouBanSpider;
import club.ruanx.spider.common.enumeration.SpiderTypeEnum;
import club.ruanx.spider.common.message.SpiderMessageSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Set;

/**
 * @author 阮胜
 * @date 2018/12/23 13:48
 */
@Component
@Slf4j
public class AsyncSpider {
    private final DouBanSpider douBanSpider;
    private final SpiderMessageSender spiderMessageSender;

    public AsyncSpider(DouBanSpider douBanSpider, SpiderMessageSender spiderMessageSender) {
        this.douBanSpider = douBanSpider;
        this.spiderMessageSender = spiderMessageSender;
    }

    @Async
    public void startDoubanSpider(String type, int limit, int pageStart) throws IOException {
        douBanSpider.process(type, limit, pageStart);
        sendMsgToRabbit();
    }

    @Async
    public void startWithIdSet(Set<String> idSet) {
        douBanSpider.fetchByIds(idSet);
        sendMsgToRabbit();
    }

    private void sendMsgToRabbit() {
        log.info("发送消息到RabbitMQ队列,通知服务器爬虫数据已经就绪.");
        spiderMessageSender.outputSend(MessageData.builder().tag(SpiderTypeEnum.DOUBAN.getTag()).build());
    }
}
